package com.sxc.upload;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;

    @WebServlet("/uploadServlet")
    @MultipartConfig //文件上传表单一定要加这个注释
    public class uploadServlet extends HttpServlet {

        @Override
        protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            System.out.println("文件上传....");
            // 设置请求编码格式
            req.setCharacterEncoding("UTF-8");
            // 获取普通表单项
            String username = req.getParameter("username");
            System.out.println("username: " + username);
            // 获取Part对象（Serlet将mutipart/form-data的POST请求封装成Part对象）
            Part part = req.getPart("myfile");
            // 通过part对象得到上传的文件名
            String fileName = part.getSubmittedFileName();
            System.out.println("上传文件名: " + fileName);

            String realPath = req.getServletContext().getRealPath("/");
            System.out.println("文件存放路径: " + realPath);
            // 上传文件到指定目录
            part.write(realPath + "/" + fileName);

        }
    }
